var height = $(document.body).height()+"px";
//用react封装
var currentpage = 1,totlepage = 1,i,pagecount=15;//分页的当前页和总的页数
//表单数据：学校页面的对应注解：学校名称 考勤区域  隶属地区 设备自定义套餐（扩展）学校id
var packageData = [];
//表单的最高高度、当前第几页、总页数、总行数、设备投放切换、箱号
var otherData = {maxHeight:'0px',currentpage:0,totlepage:0,totlerows:0,pageLeft:0,pageRight:0,view:'',boxOrdevice:'device',batchNumber:'',upBatchNumber:''};
//套餐列表 套餐名称、赠送时间，单位月、试用期，单位天、套餐费用、（新增add、修改update）
var setMealList = {packagename:'',freetime:'',trytime:'',fee2:'',type:'add'};
var Page = React.createClass({
    render: function () {
        {
            var items = [],
                svar = this;
            var onPageClickArray = [this.onPageClick];
            if(totlepage < 6){
                for(i = 1;i <= totlepage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totlepage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totlepage-2;i <= totlepage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }
        }
        return (
            <div className="tableInfo-page">
                <div className="page-number">每页{pagecount}条</div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <ol className="page-limit-ol">
                            <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)}><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                            {
                                items.map(function (item) {
                                    return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)} className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                                })
                            }
                            <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)} ><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                        </ol>
                    </ol>
                </div>
            </div>
        );
    },
});
//设备套餐
var DeviceSetMealTable = React.createClass({
    render: function () {
        return (
            <tr>
                <td style={{width: '20%'}}>{this.props.packagename}</td>
                <td style={{width: '60%'}}>{this.props.packagecontent}</td>
                <td style={{width: '20%'}}><div className="trButton" onClick={this.props.onClickEdit}>设置</div></td>
            </tr>
        );
    }
});
//新增或修改设备套餐
var AddDeviceSetMeal = React.createClass({
    //关闭弹出层
    onClickHidePop: function () {
        $(".initializeMenu", window.parent.document).hide();//父页面的遮罩
        $(".addDeviceSetMeal").hide();
        $(".errorMsg").hide();
    },
    //保存套餐
    onClockSavePackage: function () {
        var svar = this;
        if($("#package_packagename").val()==""){
            $(".packagename-error").show();
            return;
        }
        if($("#package_fee2").val()==""){
            $(".fee2-error").show();
            return;
        }
        var id=$("#package_id").val();
        var url=serverUrl+'/packageManage/addPackage.json';
        var param="param={";
        if(id!=null && id!=""){
            param = getJsonDataNotEmpty(param,"id",$("#package_id").val());
            url=serverUrl+'/packageManage/modifyPackage.json';
        }
        param = getJsonDataNotEmpty(param,"packagename",$("#package_packagename").val());
        param = getJsonDataNotEmpty(param,"freetime",$("#package_freetime").val());
        param = getJsonDataNotEmpty(param,"trytime",$("#package_trytime").val());
        param = getJsonDataNotEmpty(param,"fee2",$("#package_fee2").val());
        param += "}";
        suixun.showLoding();//显示加载中
        $.ajax({
            url:url,
            data:param,
            dataType:'json',
            success:function (data) {
                suixun.hideLoding(200);//隐藏加载中
                if(data!=null && data.code == 200){
                    suixun.alert("操作成功",function (data) {
                        if(data){
                            svar.onClickHidePop();
                            svar.props.onPageClick(currentpage);
                        }
                    });

                } else {
                    suixun.alert((data!=null && data.msg!=null)?data.msg:"操作失败");
                }
            }.bind(this),
            error: function (req,info,error) {
                top.location.href = invalidUrl;
            }
        });
    },
    //验证
    onBlurInput: function (e) {
        var classname = e.target.getAttribute("data-error");
        if($(e.target).val() == ''){
            $("."+classname+"").show();
        }else{
            $("."+classname+"").hide();
        }
    },
    render: function () {
        return (
            <div  className="pop popPhone addDeviceSetMeal popModel">
                <div className="model"></div>
                <div className="pop-info popModel-info">
                    <div className="pop-title popModel-title">
                                <span className="pop-title-content popModel-title-content">
                                    <span className="pop-title-content-solid-left popModel-title-content-solid-left"></span>
                                    <span className="pop-title-value">编辑设备套餐</span>
                                    <span className="pop-title-content-solid-right popModel-title-content-solid-right"></span>
                                </span>
                        <span className="pop-title-img popPhone-title-img" onClick={this.onClickHidePop}><img src="../img/icon/close.png" alt="关闭"/></span>
                        <input type="hidden" name="package_id" id="package_id" />
                    </div>
                    <div className="pop-body popModel-body">

                        <div className="popModel-body-input">
                            <span className="popModel-body-input-title">套餐名称</span>
                            <span className="popModel-body-input-content">
                                        <input className="input-content " onBlur={this.onBlurInput} data-error="packagename-error" id="package_packagename" type="text" placeholder="请输入套餐名称" />
                                    </span>
                            <div className="errorMsg packagename-error" ></div>
                        </div>

                        <div className="popModel-body-input">
                            <span className="popModel-body-input-title">年费</span>
                            <span className="popModel-body-input-content">
                                        <input className="input-content " data-error="fee2-error" onBlur={this.onBlurInput} id="package_fee2" type="text" placeholder="请输入套餐年费（元）"  />
                                    </span>
                            <div className="errorMsg fee2-error" ></div>
                        </div>

                        <div className="popModel-body-input">
                            <span className="popModel-body-input-title" style={{backgroundImage: "url()"}}>赠送时间</span>
                            <span className="popModel-body-input-content">
                                        <input className="input-content "  id="package_freetime" type="text" placeholder="请输入赠送时间（月）"  />
                                    </span>
                        </div>

                        <div className="popModel-body-input">
                            <span className="popModel-body-input-title" style={{backgroundImage: "url()"}}>试用期</span>
                            <span className="popModel-body-input-content">
                                        <input className="input-content "  id="package_trytime" type="text" placeholder="请输入试用期（天）"  />
                                    </span>
                        </div>

                    </div>
                    <div className="popModel-button" style={{marginTop:"20px"}}>
                        <span className="popModel-button-ok" onClick={this.onClockSavePackage}>确定</span>
                    </div>
                </div>
            </div>
        );
    }
});
//设备套餐
var DeviceSetMeal = React.createClass({
    onPageClick: function (num) {
        //分页-调用ajac然后把数据查询出来:获取name的值
        //计算currentpage
        suixun.showLoding();//显示加载中
        var onPageLeft = 0,onPageRight = 1;
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totlepage){
            currentpage ++;
        }
        //修改左右的按钮
        if(currentpage == totlepage && totlepage == 1){
            onPageLeft = 0;
            onPageRight = 0;
        }else if(currentpage == totlepage && totlepage > 1){
            onPageLeft = 1;
            onPageRight = 0;
        }else if(1 < currentpage && currentpage < totlepage){
            onPageLeft = 1;
            onPageRight = 1;
        }
        packageData = [];
        var param="param={pagenumber:"+currentpage+",pagecount:"+pagecount;
        param = getJsonDataNotEmpty(param,"packagename",$("#packagename_search").val());
        param += "}";
        packageData = [];
        //执行ajax获取数据然后组装
        $.ajax({
            url:serverUrl+'/packageManage/queryPackageList.json',
            data:param,
            dataType:'json',
            success:function (data) {
                suixun.hideLoding();//隐藏加载中
                if(data.code == 200){
                    for(var i=0;i<data.info.queryresult.length;i++){
                        var obj=data.info.queryresult[i];
                        packageData[i] = {id:obj.id,packagename:obj.packagename,packagecontent:obj.packagecontent,fee2:obj.fee2,freetime:obj.freetime,trytime:obj.trytime,status:obj.status};
                    }
                    otherData = {maxHeight:height,currentpage:currentpage,totlepage:data.info.totlepage,totlerows:data.info.totlerows,pageLeft:onPageLeft,pageRight:onPageRight,view:'deviceSetMeal',batchNumber:'',upBatchNumber:''};
                    this.setState({packageData:packageData,otherData:otherData});
                }
            }.bind(this),
            error: function (req,info,error) {
                top.location.href = invalidUrl;
            }
        });
    },
    //新增套餐
    onClickAdd: function () {
        $("#package_id").val("");
        $("#package_packagename").val("");
        $("#package_fee2").val("");
        $("#package_freetime").val("");
        $("#package_trytime").val("");
        $(".addDeviceSetMeal").show();
        $(".pop-title-value").html("新增设备套餐");
    },
    //编辑
    onClickEdit: function (info) {
        $("#package_id").val(info[0]);
        $("#package_packagename").val(info[1]);
        $("#package_fee2").val(info[2]);
        $("#package_freetime").val(info[3]);
        $("#package_trytime").val(info[4]);
        $(".pop-title-value").html("编辑设备套餐");
        $(".addDeviceSetMeal").show();
    },
    render: function () {
        {
            var svar = this;
            var clickArray = [this.onClickEdit];
            var Tabels = packageData.map(function (data) {
                return (
                    <DeviceSetMealTable key={data.id} onClickEdit={clickArray[0].bind(svar,[data.id,data.packagename,data.fee2,data.freetime,data.trytime])}  id={data.id}  packagecontent={data.packagecontent}  packagename={data.packagename}  />
                )
            })
        }
        return (
            <div>
                <AddDeviceSetMeal setMealList={this.setMealList} onPageClick={this.onPageClick}/>
                <header>
                    <div className="header-left">
                        <div className="header-left-studentInfo" data-userid="111111">套餐列表</div>
                        <div className="header-left-annotationsInfo">
                            <img src="../img/icon/annotations.png" />
                            <span className="header-left-annotations-arrowsLeft"></span>
                            <div className="header-left-annotations">这里是注释。</div>
                        </div>
                    </div>
                    <div className="header-right">
                        <div className="addButton" onClick={this.onClickAdd}>
                            <span className="addButton-img"><img src="../img/icon/add-white.png" /></span>
                            <span className="addButton-text">新增</span>
                        </div>
                    </div>
                </header>

                <div className="studentsInfo tableInfo">
                    <div className="studentsInfo-data tableInfo-data tableInfo">
                        <div className="studentsInfo-data tableInfo-data">
                            <div className="studentsInfo-data-table tableInfo-data-table" >
                                <table className="head-body head-body">
                                    <thead>
                                    <th style={{width: '20%'}}>套餐名称</th>
                                    <th style={{width: '60%'}}>套餐详情</th>
                                    <th style={{width: '20%'}}>设置</th>
                                    </thead>
                                    <tbody>
                                    {Tabels}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <Page otherData={otherData} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright" >
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        )
    },
});

//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {otherData:this.props.otherData,packageData:this.props.packageData}
    },
    componentDidMount: function () {
        //使用ajax取出数据然后组装数据列表
        this.onClickDeviceSetMeal();
    },
    //学校
    onClickSchool: function () {
        window.location.href = "../schoolManage/querySchoolList.html";
    },
    //设备投放
    onClickDeviceDelivery: function () {
        window.location.href = "../deviceInitManage/queryDeviceInitList.html";
    },
    //SIM卡投放
    onClickSIMDelivery: function () {
        window.location.href = "../simInfoManage/querySimInfoList.html";
    },
    //设备套餐
    onClickDeviceSetMeal: function () {
        otherData.view = "deviceSetMeal";

        packageData = [];
        var param="param={";
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+"");
        param += "}";
        $.ajax({
            url:serverUrl+'/packageManage/queryPackageList.json',
            data:param,
            dataType:'json',
            success:function (data) {
                suixun.hideLoding();//隐藏加载中
                if(data.code == 200){
                    for(var i=0;i<data.info.queryresult.length;i++){
                        var obj=data.info.queryresult[i];
                        packageData[i] = {id:obj.id,packagename:obj.packagename,packagecontent:obj.packagecontent,fee2:obj.fee2,freetime:obj.freetime,trytime:obj.trytime,status:obj.status};
                    }
                    var pageRight = 0;
                    if(data.info.totlepage > 1){
                        pageRight = 1;
                    }
                    otherData = {maxHeight:height,currentpage:1,totlepage:data.info.totlepage,totlerows:data.info.totlerows,pageLeft:0,pageRight:pageRight,view:'deviceSetMeal',batchNumber:'',upBatchNumber:''};
                    currentpage = 1;totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                    this.setState({packageData:packageData,otherData:otherData});
                }
            }.bind(this),
            error: function (req,info,error) {
                top.location.href = invalidUrl;
            }
        });
    },
    //设备零售价
    onClickDeviceRetailPrice: function () {
        window.location.href = "../devicePriceManage/queryDevicePriceList.html";
    },
    render: function () {
        return (
            <div className="outside" >
                <div className="deviceSetMeal tableManage-body ">
                    <div className="header-menu"  >
                        <ul>
                            <li onClick={this.onClickSchool} >学校</li>
                            <li onClick={this.onClickDeviceDelivery} >设备管理</li>
                            <li onClick={this.onClickSIMDelivery} >SIM卡管理</li>
                            <li onClick={this.onClickDeviceSetMeal} className="select">设备套餐</li>
                            <li onClick={this.onClickDeviceRetailPrice}  >设备零售价</li>
                        </ul>
                    </div>
                    <DeviceSetMeal />
                </div>
            </div>
        );
    }
});
ReactDOM.render(
    <Main  otherData={otherData} packageData={packageData} ></Main>,
    document.getElementById('tableManage')
);
